package com.mldong.flow.engine.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mldong.flow.engine.entity.ProcessSurrogate;
import com.mldong.flow.engine.mapper.ProcessSurrogateMapper;
import com.mldong.flow.engine.service.ProcessSurrogateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 流程代理服务实现
 * @author mldong
 * @date 2023/12/6
 */
@Service
@RequiredArgsConstructor
public class ProcessSurrogateServiceImpl implements ProcessSurrogateService {
    private final ProcessSurrogateMapper processSurrogateMapper;
    @Override
    public String getSurrogate(String operator, String processName) {
        List<ProcessSurrogate> processSurrogateList = processSurrogateMapper.selectList(
                Wrappers.lambdaQuery(ProcessSurrogate.class)
                .eq(ProcessSurrogate::getOperator,operator)
                .eq(ProcessSurrogate::getEnabled,1)
                .orderByDesc(ProcessSurrogate::getId)
        );
        for (ProcessSurrogate processSurrogate : processSurrogateList) {
            // 为空表示全部，优先级最高，直接返回
            if(StrUtil.isEmpty(processSurrogate.getProcessName())) {
                // 开始时间判断
                if(processSurrogate.getStartTime()!= null && processSurrogate.getStartTime().getTime() > System.currentTimeMillis()) {
                    continue;
                }
                // 结束时间判断
                if(processSurrogate.getEndTime()!= null && processSurrogate.getEndTime().getTime() < System.currentTimeMillis()) {
                    continue;
                }
                return processSurrogate.getSurrogate();
            }
        }
        // 取满足条件的最新一条
        return processSurrogateList.stream().filter(processSurrogate -> {
            // 只查询流程名称一样的
            return ObjectUtil.equals(processSurrogate.getProcessName(),processName);
        }).filter(processSurrogate -> {
            // 开始时间判断
            if(processSurrogate.getStartTime()!= null && processSurrogate.getStartTime().getTime() > System.currentTimeMillis()) {
                return false;
            }
            // 结束时间判断
            if(processSurrogate.getEndTime()!= null && processSurrogate.getEndTime().getTime() < System.currentTimeMillis()) {
                return false;
            }
            return true;
        }).map(processSurrogate -> processSurrogate.getSurrogate()).findFirst().orElse(null);
    }
}
